<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>语音识别</title>
</head>
<body>
<button id="startRecord">开始录音</button>
<button id="stopRecord" disabled>停止录音</button>
<button id="sendData" disabled>发送数据</button>
<audio id="audioPlayer" controls></audio>
<a id="downloadLink" style="display: none;">下载录音</a>
<pre id="response"></pre>

<script>
    let mediaRecorder;
    let audioChunks = [];
    let audioBlob;

    document.getElementById("startRecord").addEventListener("click", () => {
        navigator.mediaDevices.getUserMedia({ audio: { sampleRate: 16000 } })
            .then(stream => {
                mediaRecorder = new MediaRecorder(stream);
                mediaRecorder.start();

                mediaRecorder.ondataavailable = event => {
                    audioChunks.push(event.data);
                };

                mediaRecorder.onstop = () => {
                    audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                    audioChunks = [];

                    const audioUrl = URL.createObjectURL(audioBlob);
                    document.getElementById("audioPlayer").src = audioUrl;
                    document.getElementById("downloadLink").href = audioUrl;
                    document.getElementById("downloadLink").download = "recording.wav";
                    document.getElementById("downloadLink").style.display = 'block';

                    document.getElementById("sendData").disabled = false;
                };
            });

        document.getElementById("startRecord").disabled = true;
        document.getElementById("stopRecord").disabled = false;
    });

    document.getElementById("stopRecord").addEventListener("click", () => {
        mediaRecorder.stop();
        document.getElementById("startRecord").disabled = false;
        document.getElementById("stopRecord").disabled = true;
    });

    document.getElementById("sendData").addEventListener("click", () => {
        const formData = new FormData();
        formData.append("file", audioBlob);
        formData.append("temperature", "0.2");
        formData.append("response-format", "json");

        fetch("/inference", {
            method: "POST",
            body: formData,
        })
            .then(response => response.json())
            .then(data => {
                document.getElementById("response").textContent = JSON.stringify(data, null, 2);
            })
            .catch(error => {
                console.error("Error:", error);
            });
    });
</script>
</body>
</html>
